<template>
  <el-select @change="onSelected" v-model="valueModel" filterable>
    <el-option v-for="item in data" :key="item[props.valueKey]" :label="item[props.labelKey]"
      :value="item[props.valueKey]"></el-option>
  </el-select>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';

const props = withDefaults(defineProps<{
  data: object[],
  valueKey: string,
  labelKey: string
}>(), {
  data: () => []
})
const valueModel = defineModel("value", { required: true })
const labelModel = defineModel("label", { required: true })
const value = ref("")

const onSelected = (val: object) => {
  const item = props.data.find(x => x[props.valueKey] === val);
  if (item) {
    valueModel.value = item[props.valueKey];
    labelModel.value = item[props.labelKey]
  }
}

watch(() => valueModel.value, () => {
  if (valueModel.value) {
    value.value = valueModel.value.toString();
  }
}, { immediate: true })
</script>
<style lang="scss" scope></style>
